SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Jamie Swindall
-- Create date: 03/18/2011
-- Description:	Creates Display Name with Rank
-- =============================================
CREATE FUNCTION fn_DisplayName 
(
	@Format INT = 0, --| 0 = Default, LastName first(lastname, firstname mi rank); 1 = FirstName first(rank firstname mi lastname)
	@FirstName VARCHAR(MAX),
	@LastName VARCHAR(MAX),
	@MiddleName VARCHAR(MAX),
	@Rank VARCHAR(15)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
	DECLARE @DisplayName VARCHAR(MAX)
	DECLARE @_FirstName VARCHAR(MAX)
	DECLARE @_MI VARCHAR(2)
	DECLARE @_LastName VARCHAR(MAX)
	DECLARE @_Rank VARCHAR(15)
	DECLARE @_Seperator VARCHAR(2)

	SELECT @_Seperator =	CASE @Format
								WHEN 0 THEN ', '
								ELSE ' '
							END
	SELECT @_LastName =		ISNULL(@LastName + @_Seperator, '')
	SELECT @_FirstName =	ISNULL(@FirstName + ' ', '')
	SELECT @_MI =			ISNULL(SUBSTRING(@MiddleName,1,1) + ' ', '')
	SELECT @_Rank =			CASE @Format
								WHEN 0 THEN ISNULL(' ' + @Rank, '')
								ELSE ISNULL(@Rank + ' ', '')  
							END

	SELECT @DisplayName =	CASE @Format
								WHEN 0 THEN @_LastName + @_FirstName + @_MI + @_Rank
								ELSE @_Rank + @_FirstName + @_MI + @_LastName
							END

	RETURN @DisplayName
END
GO

/*

SELECT [dbo].[fn_DisplayName] (
	1
   ,'FirstName'
  ,'LastName'
  ,'MiddleName'
  ,'Rank')



*/